package com.screen.screendisplay.service.impl.al;

import com.screen.screendisplay.entity.al.AlProdoperSales;
import com.screen.screendisplay.mapper.al.AlProdoperSalesMapper;
import com.screen.screendisplay.service.al.AlProdoperSalesService;
import com.screen.screendisplay.vo.al.AlProdoperSalesVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 销售情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class AlProdoperSalesServiceImpl extends ServiceImpl<AlProdoperSalesMapper, AlProdoperSales> implements AlProdoperSalesService {

    @Override
    public List<AlProdoperSalesVO> getLiquidSalesData() {
        return getSalesDataByCategory((byte) 0);
    }

    @Override
    public List<AlProdoperSalesVO> getIngotSalesData() {
        return getSalesDataByCategory((byte) 1);
    }

    /**
     * 根据销售品类获取销售数据
     *
     * @param salesCategory 销售品类：0-铝液,1-铝锭
     * @return 销售情况VO列表
     */
    private List<AlProdoperSalesVO> getSalesDataByCategory(Byte salesCategory) {
        // 查询最近12个月的销售数据
        List<AlProdoperSales> salesList = baseMapper.getRecentSalesData(salesCategory);
        
        if (salesList == null || salesList.isEmpty()) {
            return new ArrayList<>();
        }

        // 反转列表，使其按时间顺序排列（从旧到新）
        Collections.reverse(salesList);

        // 转换为VO对象
        List<AlProdoperSalesVO> voList = new ArrayList<>();
        for (AlProdoperSales sales : salesList) {
            AlProdoperSalesVO vo = new AlProdoperSalesVO();
            
            // 复制基本属性
            vo.setYear(sales.getYear());
            vo.setMonth(sales.getMonth());
            vo.setMonthPlanSales(sales.getMonthPlanSales());
            vo.setMonthActualSales(sales.getMonthActualSales());
            vo.setMonthCompletionRate(sales.getMonthCompletionRate());
            vo.setMonthOverShort(sales.getMonthOverShort());
            vo.setYoySalesRate(sales.getYoySalesRate());

            // 查询去年同期数据，计算历史同期实际销售量
            Integer lastYear = sales.getYear() - 1;
            AlProdoperSales historicalSales = baseMapper.getHistoricalSalesData(
                    salesCategory, lastYear, sales.getMonth());
            
            if (historicalSales != null && historicalSales.getMonthActualSales() != null) {
                vo.setHistoricalActualSales(historicalSales.getMonthActualSales());
            } else {
                // 如果没有历史数据，设置为0
                vo.setHistoricalActualSales(BigDecimal.ZERO);
            }

            voList.add(vo);
        }

        return voList;
    }

}
